<script>
import { getUserInfoService, updateUserInfoService } from '../api/user.js'; // 导入接口
import { ref, onMounted } from 'vue'; // 导入 Vue 3 的 ref 和 onMounted
import { ElMessage } from 'element-plus';
export default {
    setup() {
        const userName = ref(''); // 存储用户名
        const userInfo = ref({});  // 使用 ref 创建响应式数据
        const showRechargeDialog = ref(false);  // 控制充值弹框显示与否
        const rechargeAmount = ref(0);  // 存储选择的充值金额
        const availableAmounts = [50, 100, 200, 500];  // 可选择的充值金额

        // 获取用户信息的方法
        const fetchUserInfo = async () => {
            try {
                const response = await getUserInfoService(userName); // 获取 userName 的值
                console.log(response);
                if (response.data) {
                    userInfo.value = response.data;  // 更新 userInfo
                }
            } catch (error) {
                console.error('获取用户信息失败', error); // 输出详细的错误信息
                ElMessage.error(`获取用户信息失败: ${error.message || error}`); // 显示详细的错误信息
            }
        };

        // 获取 cookie 中的某个值
        const getCookie = (name) => {
            const nameEQ = name + "=";
            const ca = document.cookie.split(';');
            for (let i = 0; i < ca.length; i++) {
                let c = ca[i].trim();
                if (c.indexOf(nameEQ) === 0) {
                    return c.substring(nameEQ.length, c.length);
                }
            }
            return null;
        };

        // 在页面加载时检查是否有存储的 username
        onMounted(() => {
            const storedUsername = getCookie('username');
            console.log(storedUsername);
            if (storedUsername) {
                userName.value = storedUsername; // 自动填充 username
                fetchUserInfo(); // 调用获取用户信息的接口
            }
        });

        // 充值操作
        const handleRecharge = () => {
            showRechargeDialog.value = true;
        };
        const handleCloseRechargeDialog = () => {
            showRechargeDialog.value = false;
        };
        // 确认充值，充值成功后调用更新用户信息接口
        const handleConfirmRecharge = async () => {
            if (rechargeAmount.value > 0) {
                try {
                    // 调用充值接口
                    const response = await updateUserInfoService({ userName, permission: 1 });

                    // 假设返回的 response.code 表示是否成功
                    if (response.code === 0) {
                        // 充值成功
                        ElMessage.success(`充值成功！充值金额：${rechargeAmount.value}元`);
                        fetchUserInfo();
                        // 关闭弹框
                        handleCloseRechargeDialog();
                    } else {
                        // 充值失败
                        ElMessage.error(response.message || '充值失败，请稍后再试');
                    }
                } catch (error) {
                    // 处理请求错误
                    ElMessage.error('充值失败，请稍后再试');
                    console.error('充值请求错误:', error);
                }
            } else {
                // 如果金额为 0 或者没有选择金额，提示用户
                ElMessage.error('请选择充值金额');
            }
        };

        // 搜索记录点击事件
        const handleRowClick = (row) => {
            const recordId = row.recordId;
            // 这里可以进行页面跳转，假设你想跳转到 `/record/:id` 页面
            this.$router.push({ path: `/record/${recordId}` });
        };

        return {
            userInfo,
            fetchUserInfo,
            userName,
            showRechargeDialog,
            rechargeAmount,
            availableAmounts,
            handleRecharge,
            handleCloseRechargeDialog,
            handleConfirmRecharge,
            handleRowClick,
        };
    }
};
</script>

<template>
    <div class="main-user">
        <div class="Info">
            <el-card style="max-width: 80%; margin-left: 10%; padding: 20px;">
                <el-descriptions title="个人空间" direction="vertical" border style="margin-top: 20px;">
                    <el-descriptions-item :rowspan="2" :width="140" label="Photo" align="center">
                        <el-image style="width: 100px; height: 100px; border-radius: 50%;"
                            src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                    </el-descriptions-item>
                    <el-descriptions-item label="用户名">{{ userInfo.userName }}</el-descriptions-item>
                    <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
                    <el-descriptions-item label="用户身份" class="user-identity">
                        <span
                            :style="userInfo.permission === 1 ? { color: 'red', fontWeight: 'bold' } : { color: 'black' }">
                            {{ userInfo.permission === 1 ? 'VIP' : '普通用户' }}
                        </span>
                        <el-button v-if="userInfo.permission === 0" type="primary" @click="handleRecharge"
                            class="recharge-btn">
                            开通会员
                        </el-button>
                    </el-descriptions-item>
                    <el-descriptions-item label="注册时间">{{ userInfo.registerDate }}</el-descriptions-item>
                    <el-descriptions-item label="搜索记录">
                        <el-table :data="userInfo.records" height="250" style="width: 100%;"
                            @row-click="handleRowClick">
                            <el-table-column prop="recordId" label="记录ID" width="250" />
                            <el-table-column prop="date" label="日期" width="250" />
                            <el-table-column prop="keyword" label="关键词" />
                        </el-table>
                    </el-descriptions-item>
                </el-descriptions>
            </el-card>
        </div>

        <div v-if="showRechargeDialog" class="recharge-dialog">
            <div class="dialog-overlay" @click="handleCloseRechargeDialog"></div>
            <div class="dialog-content">
                <h2>充值页面</h2>
                <p>请选择充值金额：</p>
                <div class="amount-options">
                    <label v-for="amount in availableAmounts" :key="amount">
                        <input type="radio" v-model="rechargeAmount" :value="amount" />
                        {{ amount }} 元
                    </label>
                </div>
                <div class="dialog-actions">
                    <button @click="handleConfirmRecharge" class="confirm-btn">确认充值</button>
                    <button @click="handleCloseRechargeDialog" class="cancel-btn">取消</button>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.main-user {
    font-family: 'Arial', sans-serif;
}

.user-identity {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.recharge-btn {
    margin-left: 10px;
}

.Info {
    margin-top: 30px;
}

.el-card {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-descriptions-item label {
    font-weight: bold;
}

.el-table th {
    background-color: #f2f2f2;
}

.histroy {
    margin-top: 30px;
}

/* 自定义弹框样式 */
.recharge-dialog {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.dialog-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    cursor: pointer;
}

.dialog-content {
    background: white;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
    width: 300px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
    z-index: 1001;
}

.amount-options {
    margin-bottom: 20px;
}

.amount-options label {
    display: block;
    margin-bottom: 10px;
}

.dialog-actions button {
    padding: 8px 16px;
    margin: 5px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.confirm-btn {
    background-color: #4caf50;
    color: white;
}

.cancel-btn {
    background-color: #f44336;
    color: white;
}
</style>